//
//  WJHomeViewController.swift
//  WJWEIBO
//
//  Created by 文杰 许                       on 2017/5/11.
//  Copyright © 2017年 文杰 许                      . All rights reserved.
//

import UIKit

fileprivate let myCell = "myCell"

class WJHomeViewController: WJBaseViewController {
    
    /// viewmodel
    lazy var listViewModel = WJWBStatusViewModel()

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }
    
    /// 加载数据
    override func loadData()
    {
        print("准备刷新，最后一条\(listViewModel.statusList.last?.text ?? "没有更多")")
        listViewModel.loadStatusData(pullUP: isPullup) { (isSuccess, hasMoreData) in
            if ((self.refreshControl != nil) && (self.refreshControl?.isRefreshing)!)
            {
                self.refreshControl?.endRefreshing()
            }
            self.isPullup = false
            if hasMoreData
            {
                self.tableView?.reloadData()
            }
        }
    }
    
    /// 刷新数据
    override func refreshData()
    {
        if listViewModel.statusList.count > 0
        {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1)
            {
                self.loadData()
            }
        }
        else
        {
            loadData()
        }
    }

    /// 展示好友
    @objc fileprivate func showFriends()
    {
        print(#function)
        
        let vc = WJDemoViewController()
        
        navigationController?.pushViewController(vc, animated: true)
    }
}

/// 设置界面
extension WJHomeViewController
{
    override func setupTableView()
    {
        super.setupTableView()
        
        leftBarItem.isHidden = false
        leftBarItem .setTitle("好友", for: .normal)
        leftBarItem .addTarget(self, action: #selector(showFriends), for: .touchUpInside)
        
        //注册cell
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: myCell)
    }
}

/// 数据源代理方法
extension WJHomeViewController
{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: myCell, for: indexPath)
        
        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text
        
        cell.selectionStyle = .none
        
        return cell
    }
}
